<template>
  <v-col style="flex: none; width: 80px;"
    class="d-flex flex-column align-center justify-space-between py-6 bg-surface elevation-2 tabs-container">

    <!-- 顶部 Tabs -->
    <div class="d-flex flex-column align-center" style="row-gap: 1.5rem;">
      <div v-for="item in tabs" :key="item.value" @click="handleTabClick(item)"
        class="d-flex flex-column align-center text-caption cursor-pointer tab-item" :class="[
          internalTab === item.value ? 'text-primary font-weight-bold' : 'text-medium-emphasis',
          activeTab === item.value ? 'tab-bounce' : ''
        ]" style="transition: color 0.2s">
        <template v-if="item.icon.startsWith('mdi-')">
          <v-icon size="28" class="mb-1">{{ item.icon }}</v-icon>
        </template>
        <template v-else>
          <v-avatar size="32" class="mb-1">
            <img :src="item.icon" alt="头像" />
          </v-avatar>
        </template>
        {{ item.label }}
      </div>
    </div>

    <!-- 主题切换按钮 -->
    <div class="d-flex flex-column align-center cursor-pointer text-medium-emphasis" @click="toggleTheme">
      <v-icon size="28" class="mb-1 transition-rotate" :class="isDark ? 'rotate-180' : ''">
        {{ isDark ? 'mdi-white-balance-sunny' : 'mdi-weather-night' }}
      </v-icon>
      <span class="text-caption">{{ isDark ? '明亮' : '暗黑' }}</span>
    </div>

    <!-- 注销确认对话框 -->
    <v-dialog v-model="showLogoutDialog" max-width="300">
      <v-card>
        <v-card-title class="text-h6">确认注销</v-card-title>
        <v-card-text>确定要退出登录吗？</v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="showLogoutDialog = false">取消</v-btn>
          <v-btn color="error" @click="logout">注销</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-col>
</template>

<script setup lang="ts">
import { ref, watch, computed, onMounted } from 'vue'
import { useTheme } from 'vuetify'
import axios from 'axios'

const props = defineProps<{ modelValue?: string }>()
const emit = defineEmits(['update:tab'])

const theme = useTheme()
const isDark = computed(() => theme.global.current.value.dark)
const toggleTheme = () => {
  theme.global.name.value = isDark.value ? 'light' : 'dark'
}

// 登录信息状态
const userId = ref<number | null>(null)
const avatarUrl = ref<string>('') // 可替换为真实头像地址
const isLoggedIn = computed(() => !!userId.value && !!localStorage.getItem('jwt_token'))

const showLogoutDialog = ref(false)

function checkLoginStatus() {
  const uid = localStorage.getItem('user_id')
  const token = localStorage.getItem('jwt_token')
  if (uid && token) {
    userId.value = Number(uid)
  } else {
    userId.value = null
  }
}

onMounted(() => {
  checkLoginStatus()
})

const tabs = computed(() => {
  return [
    { value: 'friends', icon: 'mdi-account', label: '好友' },
    { value: 'groups', icon: 'mdi-account-group', label: '群聊' },
    isLoggedIn.value
      ? {
        value: 'profile',
        icon: avatarUrl.value || 'mdi-account-circle',
        label: `ID: ${userId.value}`
      }
      : {
        value: 'login',
        icon: 'mdi-login',
        label: '登录'
      }
  ]
})

const internalTab = ref(props.modelValue || 'friends')
watch(() => props.modelValue, (newVal) => {
  if (newVal && newVal !== internalTab.value) {
    internalTab.value = newVal
  }
})

const activeTab = ref<string | null>(null)

function selectTab(value: string) {
  internalTab.value = value
  emit('update:tab', value)
  activeTab.value = value
  setTimeout(() => {
    activeTab.value = null
  }, 150)
}

// 区分点击普通 tab 还是头像 tab
function handleTabClick(item: { value: string; icon: string; label: string }) {
  if (item.value === 'profile') {
    showLogoutDialog.value = true
  } else {
    selectTab(item.value)
  }
}

async function logout() {
  try {
    const token = localStorage.getItem('jwt_token') || ''
    await axios.post(
      'http://localhost:8080/api/user/logout',
      null, // POST 请求体为空
      {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }
    )
    console.log('✅ 注销成功')
  } catch (err) {
    console.warn('❌ 注销失败（可能 token 已失效）')
  }

  // 清除本地数据并刷新
  localStorage.removeItem('jwt_token')
  localStorage.removeItem('user_id')
  location.reload()
}
</script>


<style scoped>
.tab-bounce {
  animation: tabBounce 300ms ease;
}

@keyframes tabBounce {
  0% {
    transform: scale(1);
  }

  40% {
    transform: scale(0.9);
  }

  100% {
    transform: scale(1);
  }
}
</style>
